﻿namespace SenenFernandez.SmartExtensionMethods
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Runtime.Versioning;

    /// <summary>
    /// Screen Manager for Windows Presentation Foundation.
    /// </summary>
    public static class SmartScreenManager
    {
        private static readonly HandleRef NullHandleReference = new HandleRef(null, IntPtr.Zero);

        [DllImport("user32.dll", ExactSpelling = true)]
        [ResourceExposure(ResourceScope.None)]
        private static extern bool EnumDisplayMonitors(HandleRef handle, IntPtr clip, DisplayEnumProc lpfnEnum, IntPtr data);

        private delegate bool DisplayEnumProc(IntPtr display, IntPtr handle, IntPtr parentDisplay, IntPtr parameters);

        /// <summary>
        /// Enumerates display monitors that intersect a region formed by the intersection of a specified clipping rectangle and the visible region of a device context.
        /// </summary>
        public static IEnumerable<Display> Monitors
        {
            get
            {
                var closure = new DisplayCallback();
                var proc = new DisplayEnumProc(closure.Callback);
                EnumDisplayMonitors(NullHandleReference, IntPtr.Zero, proc, IntPtr.Zero);
                return closure.Monitors;
            }
        }

        /// <summary>
        /// Gets the default display monitor.
        /// </summary>
        public static Display Primary
        {
            get { return Monitors.Where(source => source.IsPrimary).FirstOrDefault(); }
        }
    }
}